package main

import (
	"strings"

	"github.com/gorilla/websocket"
)

type User struct {
	Name         string
	Conn         *websocket.Conn
	Server       *Server
	C            chan string
	CurrentGroup string
}

func NewUser(conn *websocket.Conn, server *Server, name string) *User {
	user := &User{
		Name:         name,
		Conn:         conn,
		Server:       server,
		C:            make(chan string),
		CurrentGroup: "",
	}
	go user.listenMessage()
	return user
}

func (u *User) Online() {
	u.Server.mapLock.Lock()
	u.Server.OnlineMap[u.Name] = u
	u.Server.mapLock.Unlock()
	u.Server.Broadcast(u, "上线了")
}

func (u *User) Offline() {
	u.Server.mapLock.Lock()
	delete(u.Server.OnlineMap, u.Name)
	u.Server.mapLock.Unlock()

	if u.CurrentGroup != "" {
		u.Server.groupLock.Lock()
		group := u.Server.Groups[u.CurrentGroup]
		delete(group.Members, u.Name)
		u.Server.groupLock.Unlock()
	}
	u.Server.Broadcast(u, "下线了")
}

func (u *User) DoMessage(msg string) {
	if msg == "who" {
		u.Server.mapLock.RLock()
		for _, user := range u.Server.OnlineMap {
			u.SendMsg("[在线] " + user.Name)
		}
		u.Server.mapLock.RUnlock()
		return
	}

	if strings.HasPrefix(msg, "rename|") {
		newName := strings.TrimPrefix(msg, "rename|")
		u.Server.mapLock.Lock()
		if _, ok := u.Server.OnlineMap[newName]; ok {
			u.SendMsg("用户名已存在")
		} else {
			delete(u.Server.OnlineMap, u.Name)
			u.Name = newName
			u.Server.OnlineMap[u.Name] = u
			u.SendMsg("用户名更新为：" + u.Name)
		}
		u.Server.mapLock.Unlock()
		return
	}

	if strings.HasPrefix(msg, "to|") {
		parts := splitN(msg, "|", 3)
		if len(parts) != 3 {
			u.SendMsg("格式错误，应为 to|用户名|内容")
			return
		}
		target, ok := u.Server.OnlineMap[parts[1]]
		if !ok {
			u.SendMsg("用户不存在")
			return
		}
		target.SendMsg("[私聊] " + u.Name + ": " + parts[2])
		return
	}

	if strings.HasPrefix(msg, "group|") {
		u.handleGroupMessage(msg)
		return
	}

	u.Server.Broadcast(u, msg)
}

func (u *User) SendMsg(msg string) {
	u.C <- msg
}

func (u *User) listenMessage() {
	for msg := range u.C {
		u.Conn.WriteMessage(websocket.TextMessage, []byte(msg))
	}
}
